import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";
import IndexView from "@/views/IndexView.vue";
import UserView from "@/views/UserView.vue";
import StudentView from "@/views/StudentView.vue";
import ScoreView from "@/views/ScoreView.vue";
import HomeView from "@/views/HomeView.vue";
import ClazzView from "@/views/ClazzView.vue";

Vue.use(VueRouter)

//  路由列表    to   组件的映射关系表
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  {
    path: '/index',
    name: 'index',
    redirect:'/index/home',   //  路径重定向
    component: IndexView,
    children:[
      {
        path: 'user',
        name: 'user',
        component: UserView
      },
      {
        path: 'student',
        name: 'student',
        component: StudentView
      },
      {
        path: 'score',
        name: 'score',
        component: ScoreView
      },
      {
        path: 'home',
        name: 'home',
        component: HomeView
      },
      {
        path: 'clazz',
        name: 'clazz',
        component: ClazzView
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫  to  去哪里  from  哪里来     next是一个函数  控制是否放行
router.beforeEach((to, from, next) => {

  // 判定用户访问的是不是登录页和注册页  如果是 则直接放行 
  if (to.path=='/login' || to.path=='/register'){
    next()
    return
  }

  // 用户如果认证通过，则在本地会话中会存储一个用户名  则可以根据这一特点判定用户是否已经认证
  var username = sessionStorage.getItem("username");   //string  js中非空就是true   undefined   false   0  false
  if (!username){
      next('/login')
     return;
  }

  next()

})



export default router
